package com.bkgy.controller.tbCal1630FlatnessWarn.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bkgy.controller.tbCal1630FlatnessWarn.entity.FlatnessWarn;
import com.bkgy.controller.tbCal1630FlatnessWarn.service.IFlatnessWarnService;
import com.bkgy.jobs.dto.FlatnessHmiBaseRequest;
import com.bkgy.modular.httppost.HttpClientService;
import com.bkgy.sys.common.entity.ResultData;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/flatness")
public class FlatnessWarnController {
    @Autowired
    private HttpClientService httpClient;
    @Autowired
    private IFlatnessWarnService flatService;
    @Value("${flatHmi}")
    private String url;

    @Operation(summary = "连退平整机", description = "获取预警内容")
    @PostMapping("/getEarlyWarning")
    public ResultData<FlatnessWarn> getEarlyWarning() {
        FlatnessWarn obj = null;
        int i = 0;
        while (true) {
            obj = getFlatnessWarn();
            if (obj == null) {
                log.warn("没有正确获得中间件对象");
            } else break;
            if (++i >= 3) {
                log.warn("连续3次获取不到请求结果");
                break;
            }
        }

        return ResultData.ResultDataSuccess(obj);
    }

    private FlatnessWarn getFlatnessWarn() {
        FlatnessWarn warnObj = new FlatnessWarn();

        List<Map<String, String>> mapList = new ArrayList<>();
        FlatnessHmiBaseRequest hmiBaseRequest = new FlatnessHmiBaseRequest();
        String[] keyArr = new String[]{"CAL1_ROLL.Counter", "CAL1_ROLL.CoilNo", "CAL1_ROLL.Fspare1", "CAL1_ROLL.Fspare2",
                "CAL1_ROLL.Fspare3", "CAL1_ROLL.Fspare5", "SPMsettime"};
        for (String key : keyArr) {
            Map map = new HashMap();
            map.put("tagName", key);
            map.put("timestamp", 0);
            mapList.add(map);
        }
        hmiBaseRequest.setBody(mapList);
        String json = JSON.toJSONString(hmiBaseRequest);
        String respStr = httpClient.postJsonRequest(url, json, false, "");
        JSONObject respObj = JSONObject.parseObject(respStr);
        if (respObj == null) {
            log.warn("中间件请求返回对象为空");
            return null;
        }
        int code = respObj.getIntValue("code");
        if (code == 200) {
            JSONArray results = respObj.getJSONArray("results");
            Map<String, Object> map = new HashMap<>();
            for (int i = 0; i < results.size(); i++) {
                String k = results.getJSONObject(i).getString("tagName");
                Object v = results.getJSONObject(i).get("value");
                map.put(k, v);
            }

            //请求返回的数据偶发缺项导致报错！！！
            boolean flag = true;
            for (String item : keyArr) {
                if (!map.containsKey(item)) {
                    log.warn("接收到的数据：{}", respStr);
                    log.warn("FlatnessJobs接收返回数据不齐，缺少:{}", item);
                    flag = false;
                    break;
                }
            }
            if (!flag) {
                return null;
            }

            int counter = Integer.parseInt(map.get(keyArr[0]).toString());
            warnObj.setCounter(counter);
            warnObj.setCoilNo(map.get(keyArr[1]).toString());
            BigDecimal fspare1 = BigDecimal.valueOf(Double.parseDouble(map.get(keyArr[2]).toString()));
            warnObj.setRollingForce(fspare1);
            BigDecimal fspare2 = BigDecimal.valueOf(Double.parseDouble(map.get(keyArr[3]).toString()));
            warnObj.setWorkRollBend(fspare2);
            BigDecimal fspare3 = BigDecimal.valueOf(Double.parseDouble(map.get(keyArr[4]).toString()));
            warnObj.setFollowUpCoefficient(fspare3);
            BigDecimal fspare5 = BigDecimal.valueOf(Double.parseDouble(map.get(keyArr[5]).toString()));
            warnObj.setInterMediateRollBend(fspare5);
            warnObj.setSpmSetTime(map.get(keyArr[6]).toString());
        }
        return warnObj;
    }

    private int oldCounter;
    @Scheduled(fixedRateString = "${scheduled.flatnessWarn.fixedDelay}")
    public void processRollingMillVibration() {
        FlatnessWarn flatnessWarn = getFlatnessWarn();
        if (flatnessWarn != null && flatnessWarn.getCounter() != oldCounter) {
            flatService.saveOrUpdate(flatnessWarn);
            oldCounter = flatnessWarn.getCounter();
        }
    }
}
